//
//  ZKTextView.swift
//  Weibo
//
//  Created by 郑克哥哥 on 2017/8/4.
//  Copyright © 2017年 郑克哥哥. All rights reserved.
//

import UIKit

//自定义textView
class ZKTextView: UITextView {
    
    //加载控件
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.text = "分享新新鲜事..."
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor.lightGray
        label.numberOfLines = 0
        return label
    }()
    override var font:UIFont? {
        didSet{
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    
    //设置占位文字
    var placeHolder: String?{
        didSet{
            placeHolderLabel.text = placeHolder
            
            
        }
        
        
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    
    private func setupUI() {
        
        //使用通知监听文字改变
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        addSubview(placeHolderLabel)
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        //添加约束
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 7))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
    }
    
    //MARK: -------监听文字改变-------
    @objc private func textChange(){
        //有内容就隐藏背景文字
        placeHolderLabel.isHidden = self.hasText
    }
    
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}
